import React, { useImperativeHandle } from "react";
import { Form, Input, Select, TreeSelect, Radio, InputNumber, type TreeSelectProps } from 'antd';

import { type IOuterCreateOrEditProps } from "@yaf/pro-ui";
import { getEnv  } from "@/constants";

const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 19 },
};

export const getCreateOrEdit = (menuTree: TreeSelectProps["treeData"]) => {
  const { commonStatus, commonStatusList, roleAllowUserUseType, roleAllowUserUseTypeList, adminRoleType, adminRoleTypeList } = getEnv().globalConfig;

  const CreateOrEdit: IOuterCreateOrEditProps["CreateOrEditContent"] = React.forwardRef(({ values }, actionRef) => {
    const [form] = Form.useForm();
    useImperativeHandle(actionRef, () => ({
      getFormData: () => new Promise((resolve, reject) => {
        form.validateFields().then((data) => {
          resolve(data);
        }).catch(() => {
          reject(new Error("请检查参数"));
        });
      })
    }));

    return (
      <Form
        {...layout}
        initialValues={{ 
          status: commonStatus.normal, 
          listOrder: 0, 
          type:adminRoleType.normal,
          allowUserUse: roleAllowUserUseType.notAllow,
          menuIds: [], 
          ...values 
        }}
        form={form}
      >
        <Form.Item
          label="角色名称"
          name="name"
          rules={[{ required: true, message: '请填写角色名称!' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label="角色类型"
          name="type"
          rules={[{ required: true, message: '请填写角色类型!' }]}
        >
          <Select options={adminRoleTypeList} style={{width: "100%"}}/>
        </Form.Item>
        <Form.Item
          label="允许使用"
          name="allowUserUse"
          rules={[{ required: true, message: '请选择普通用户可见性!' }]}
        >
          <Radio.Group options={roleAllowUserUseTypeList}  />
        </Form.Item>
        <Form.Item
          label="状态"
          name="status"
          rules={[{ required: true, message: '请填写状态!' }]}
        >
          <Radio.Group options={commonStatusList} />
        </Form.Item>
        <Form.Item
          label="菜单"
          name="menuIds"
          rules={[{ required: true, message: '请填写菜单!' }]}
        >
          <TreeSelect {...{
            treeCheckable: true,
            allowClear: true,
            showCheckedStrategy: TreeSelect.SHOW_ALL,
            maxTagCount: "responsive",
            treeData: menuTree
          }} />
        </Form.Item>
        <Form.Item
          label="排序"
          name="listOrder"
        >
          <InputNumber min={0} />
        </Form.Item>

        <Form.Item
          label="备注"
          name="remark"
        >
          <Input.TextArea />
        </Form.Item>
      </Form>
    )
  });

  return CreateOrEdit;
}
